<script setup lang="ts">
import { ref } from "vue"
import { onLoad } from '@dcloudio/uni-app'
import { updateGoods, getGoodsDetail } from '@/api/goods'
import { tree } from '@/api/category'
import { upload } from '@/api/file'
import type { Goods } from '@/api/goods/type'
import type { Category } from '@/api/category/type'
import { BaseResponse } from '@/api/base'
import { goodsRules } from './common'
import { toast, onAmountInput } from '@/utils/common'
import { baseUrl } from '@/config'

const goods = ref<Goods>({
  urlArr: [],
  categoryId: '',
  categoryName: '',
  name: '',
  price: '',
  url: '',
  description: ''
})
const categoryList = ref<Category[][]>([[]])
const categoryData = ref<Category[][]>([])

const pickerRef = ref()
const formRef = ref()
const currentIndex = ref([0, 0])

const loadCategoryList = async () => {
  try {
    const res: BaseResponse = await tree()
    categoryList.value = []
    categoryList.value.push(res.data)
    categoryList.value.push(res.data[0].children)
    res.data.forEach((item: Category) => {
      if (item.children) {
        categoryData.value.push(item.children)
      } else {
        categoryData.value.push([item])
      }
    })
  } catch (error) {
    toast(error.tips)
  }
}
const loadGoodsDetail = async (id: number) => {
  try {
    const res: BaseResponse = await getGoodsDetail(id)
    goods.value = res.data
    goods.value.urlArr = goods.value.url.split(',').map((item: string) => {
      return {
        url: baseUrl + item,
        status: 'success',
        message: ''
      }
    })
    categoryData.value.forEach((item: Category[], index: number) => {
      item.forEach((item: Category) => {
        if (item.id === goods.value.categoryId) {
          currentIndex.value = [index, item.id]
        }
      })
    })
  } catch (e: BaseResponse) {
    toast(e.tips)
  }
}

onLoad(async (option: any) => {
  await loadCategoryList()
  await loadGoodsDetail(option.id)
})

const openPicker = () => {
  pickerRef.value.open()
  pickerRef.value.innerIndex = currentIndex.value
}
const confirm = (e: any) => {
  goods.value.categoryId = e.value[1].id
  goods.value.categoryName = e.value[0].name === e.value[1].name ? e.value[1].name : e.value[0].name + '/' + e.value[1].name
}
const change = (e: any) => {
  const { columnIndex, index } = e
  if (columnIndex === 0) {
    pickerRef.value.setColumnValues(1, categoryData.value[index])
  }
  currentIndex.value = e.indexs
}

const afterRead = (e: any) => {
  try {
    let fileList = [].concat(e.file)
    const urlArr = goods.value.urlArr
    let fileListLen = urlArr.length
    fileList.map((item: any) => {
      urlArr.push({
        ...item,
        status: 'uploading',
        message: '上传中'
      });
    })
    fileList.forEach(async (file: any) => {
      const res: BaseResponse = await upload(file.url, file.name)
      let item = urlArr[fileListLen];
      urlArr.splice(
        fileListLen,
        1,
        Object.assign(item, {
          status: 'success',
          message: '',
          url: res.data.actionUrl
        })
      )
      fileListLen++
    })
  } catch (e) {
    toast('上传失败')
  }
}
const deletePic = (e: any) => {
  goods.value.urlArr.splice(e.index, 1)
}
const onSubmit = async () => {
  try {
    const vaild = await formRef.value.validate()
    if (!vaild) {
      return
    }
    if (!goods.value.categoryId) {
      toast('请选择商品分类')
      return
    }
    if (goods.value.urlArr.length === 0) {
      toast('请上传商品图片')
      return
    }
    goods.value.url = goods.value.urlArr.map((item: any) => item.url.substring(item.url.indexOf('files') - 1)).join(',')
    const res: BaseResponse = await updateGoods(goods.value)
    toast(res.tips)
    uni.navigateBack()
    uni.$emit('backRefresh')
  } catch (error) {
    toast(error.tips)
  }
}
</script>

<template>
  <view class="goods-create">
    <uv-form ref="formRef" labelWidth="auto" :model="goods" :rules="goodsRules">
      <uv-form-item label="商品分类" prop="categoryId" borderBottom>
        <uv-picker ref="pickerRef" :columns="categoryList" keyName="name" @confirm="confirm"
          @change="change"></uv-picker>
        <uv-input v-model="goods.categoryName" disabled disabledColor="#ffffff" placeholder="请选择分类" border="none"
          inputAlign="right" @click="openPicker"></uv-input>
        <template v-slot:right>
          <uv-icon name="arrow-right"></uv-icon>
        </template>
      </uv-form-item>
      <uv-form-item label="商品名称" prop="name" borderBottom>
        <uv-input v-model="goods.name" placeholder="请输入商品名称" border="none" inputAlign="right"></uv-input>
      </uv-form-item>
      <uv-form-item label="商品价格" prop="price" borderBottom>
        <uv-input v-model="goods.price" :formatter="onAmountInput" type="digit" placeholder="请输入商品价格" border="none"
          inputAlign="right"></uv-input>
      </uv-form-item>
      <uv-form-item label="商品图片" prop="urlArr" labelPosition="top" borderBottom>
        <uv-upload :fileList="goods.urlArr" :customStyle="{ 'margin-top': '10rpx' }" :maxCount="9"
          @afterRead="afterRead" :previewFullImage="true" @delete="deletePic"></uv-upload>
      </uv-form-item>
      <uv-form-item label="商品描述" prop="description" labelPosition="top" borderBottom>
        <uv-textarea v-model="goods.description" placeholder="请输入商品描述" border="none" inputAlign="right" maxlength="1000"
          count></uv-textarea>
      </uv-form-item>
      <view class="create-btn">
        <uv-button text="提交" color="#ff7744" @click="onSubmit"></uv-button>
      </view>
    </uv-form>
  </view>
</template>

<style lang="scss" scoped>
.goods-create {
  padding: 20rpx;
  background-color: #fff;

  .create-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100% - 40rpx);
    background-color: #fff;
    padding: 20rpx;
  }
}
</style>